package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"github.com/wejectchen/ginblog/model"
	"github.com/wejectchen/ginblog/utils/errmsg"
	"net/http"
)

func Upload(c *gin.Context) {
	_, fileHeader, _ := c.Request.FormFile("file")
	dst := viper.GetString("server.UploadPath") + fileHeader.Filename
	err := c.SaveUploadedFile(fileHeader, dst)
	code := errmsg.SUCCESS
	if err != nil {
		fmt.Println("保存文件失败", err)
		code = errmsg.ERROR
	}
	// c.JSON(http.StatusOK,gin.H{"uploading":"done","message":"success",
	//"url":"http://"+c.Request.Host+config.BaseConf.Image.Dir+file.Filename})
	//把上传的图片存数据库
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"url":     "http://" + c.Request.Host + "/" + viper.GetString("server.UploadPath") + fileHeader.Filename,
	})
}

func UpLoadCos(c *gin.Context) {
	file, fileHeader, _ := c.Request.FormFile("file")

	fileSize := fileHeader.Size

	url, code := model.UpLoadFile(file, fileSize)

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"url":     url,
	})
}
